/*
 * @Author: dingyuwen ding_yuwen@163.com
 * @Date: 2023-11-09 20:08:24
 * @LastEditTime: 2023-11-16 11:02:39
 * @LastEditors: DingYuwen 43669762+DingYuwen@users.noreply.github.com
 * @Description:
 */
import { Box, Flex, Text, useToast } from '@chakra-ui/react';
import { nanoid } from 'nanoid';
import { ReactNode, useState } from 'react';
import { useDropzone, FileRejection } from 'react-dropzone';
import { ImageUploaderTriggerContext } from './ImageUploaderTriggerContext';

export type FilePreview = (File | Blob) & { preview: string; nanoid: string };
interface ImagesUploaderProps {
  children: ReactNode;
}

export default function ImagesUploader({ children }: ImagesUploaderProps) {
  const [file, setFile] = useState<null | FilePreview>(null);

  const toast = useToast();
  const { getRootProps, getInputProps, isDragActive, open } = useDropzone({
    accept: {
      'image/png': ['.png'],
      'image/jpeg': ['.jpeg', '.jpg'],
    },
    noClick: true,
    multiple: false,
    maxSize: 10 * 1048576, // 10M的图片
    onDrop: (
      acceptedFiles: Array<File>,
      fileRejections: Array<FileRejection>
    ) => {
      if (fileRejections.length > 1) {
        const errorMsg = fileRejections
          .map((rejection) =>
            rejection.errors.map((error) => error.message).join('\n')
          )
          .join('\n');
        toast({
          title: '上传失败',
          description: errorMsg,
          status: 'error',
        });
        return;
      }
      acceptedFiles.forEach((file) => {
        Object.assign(file, {
          preview: URL.createObjectURL(file),
          nanoid: nanoid(),
        });
        setFile && setFile(file as FilePreview);
      });
    },
  });

  return (
    <ImageUploaderTriggerContext.Provider value={{ open, file, setFile }}>
      <Box
        border={isDragActive ? '4px dashed' : 'none'}
        borderColor="base.850"
        borderRadius="xl"
        flexDirection="column"
        w="full"
        h="full"
        overflow="hidden"
        position="relative"
        {...getRootProps({ className: 'dropzone' })}
      >
        <input {...getInputProps()} />
        {children}
        {isDragActive && (
          <Flex
            w="full"
            h="full"
            backdropFilter="auto"
            borderRadius="xl"
            bg="blackAlpha.400"
            transition="all 0.2s"
            align="center"
            justify="center"
            position="absolute"
            backdropBlur="8px"
            zIndex={10}
            top="0"
            left="0"
          >
            <Text fontWeight="bold" fontSize="2xl" mt="10">
              释放上传
            </Text>
          </Flex>
        )}
      </Box>
    </ImageUploaderTriggerContext.Provider>
  );
}
